package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.mathworks.engine.EngineException;
import com.mathworks.engine.MatlabEngine;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.TJszHistoryData;
import com.ruoyi.common.core.domain.entity.TReceiveStation;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IReceiveStationModeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Auther: Stanley.Y
 * @Date: 2024/6/18 15:05
 * @Description: 接收站数据管理Controller类
 * @Version 1.0.0
 */

@RestController
@Anonymous
@RequestMapping("/system/receivestation")
@Scope("prototype")
public class ReceiveStationModeController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(ReceiveStationModeController.class);

    @Autowired
    private IReceiveStationModeService receiveStationModeService;

    // 定义MatlabEngine变量
    private static MatlabEngine engine;

    static {
        try {
            engine = MatlabEngine.startMatlab();
            log.debug("***************** JSZ Matlab engine初始化开始 *****************：");
        } catch (EngineException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Value("${algorithm.jsz}")
    private String jszModelPath;

//    // 在类的构造函数中初始化全局变量
//    public ReceiveStationModeController() throws EngineException, InterruptedException {
//        this.engine = MatlabEngine.startMatlab();
//    }

    public static MatlabEngine getInstance() throws EngineException, InterruptedException {
        log.debug("Engine status =====: " + engine);
        if(engine == null){
            log.debug("getInstance创建*****************：");
            engine = MatlabEngine.startMatlab();
        }
        return engine;
    }

    /**
     * 获取默认接收站数据
     *
     * @return
     */
    @GetMapping("/getReceiveStationInfo")
    public AjaxResult getReceiveStationInfoList() {
        return success(receiveStationModeService.getReceiveStationInfoList());
    }

    /**
     * 获取默认障碍物数据
     *
     * @return
     */
    @GetMapping("/getObstacleInfo")
    public AjaxResult getObstacleInfoList() {
        return success(receiveStationModeService.getObstacleInfoList());
    }

    /**
     * 根据“数据仿真模块”和“干扰源定位”算法，计算干扰源位置。
     *
     * @param monitroArea          监测区域经纬度范围。eg：monitroArea = “113.1002,38.2311;113.123,29.3012”
     * @param interferenceDisState 干扰源生成方式(0--手动输入；1--随机)。eg：interferenceDisState = 1
     * @param interferenceNum      干扰源数量。eg：interferenceNum = 3
     * @param interferenceData     多个干扰源数据，包括每个干扰源的类型、功率、位置。
     *                             格式：类型值#功率值#位置值;...;类型值#功率值#位置值。
     *                             eg：2#40#x1,y1;3#35#x2,y2;...;4#35#xn,yn
     * @param receiveStationData   监测站数据(包括三种情况：1#监测站间隔值 or 2#监测站数量值 or 3#监测站位置值(x1,y1;x2,y2;...;xn,yn)。 1--格网部署，2--随机部署；3--位置导入)
     * @return JSONString 包含：算法调用结果：0-失败；1-成功； 计算到的干扰源位置：x1,y1,z1;x2,y2,z2;...;xn,yn,zn；随机生成的干扰源位置：x1,y1,0;x2,y2,0;...;xn,yn,0
     */
    @GetMapping("/calcInterferenceLocation")
    public AjaxResult calcInterferenceLocation(String monitroArea, int interferenceDisState, int interferenceNum,
                                               String interferenceData, String receiveStationData) {
        // 初始化模型参数对象
        double[][] monitor_Area = null; // 监测区域经纬度范围
        double[] interferenceSourcePower = null; // 干扰源功率，dBw
//        int interfereneceDisState = -1; // 干扰源生成方式：0--手动输入；1--随机
        double[][] interferencePos = null; // 干扰源位置（仅手动输入下有效）
        int[] interferenceType = null; // 干扰源类型，1—单音，2—多音，3—线性扫平，4—脉冲
        int stationDistState = 0; // 监测站分布方式，1--格网部署，2--随机部署；3--位置导入
        double stationInter = 0; // 监测站间隔(仅限StationDistState=1格网部署下有效)
        int stationNum = 0; // 监测站数量(仅限StationDistState=2随机部署下有效)
        double[][] stationPos = null; // 监测站位置（仅限StationDistState=3位置导入下有效）
        int simTime = 10; // 仿真时长，即输出的组数

        // ******************* 前端参数解析 ******************* //
        // 解析监测区域经纬度范围
        if (!"".equals(monitroArea) && monitroArea != null) {
            String[] pointArray = monitroArea.split(";");
            double point1lon = Double.parseDouble(pointArray[0].split(",")[0]);
            double point1lat = Double.parseDouble(pointArray[0].split(",")[1]);
            double point2lon = Double.parseDouble(pointArray[1].split(",")[0]);
            double point2lat = Double.parseDouble(pointArray[1].split(",")[1]);
            monitor_Area = new double[][]{{point1lon, point1lat}, {point2lon, point2lat}};
        }

        // 解析干扰源数据
        if (!"".equals(interferenceData) && interferenceData != null) {
            String[] interferenceArrays = interferenceData.split(";");
            int interCount = interferenceArrays.length;
            interferenceSourcePower = new double[interCount];
            interferenceType = new int[interCount];
            for (int s = 0; s < interCount; s++) {
                // interferenceDisState == 0 Data eg: 2#40#x1,y1;3#35#x2,y2;...;4#35#xn,yn
                // interferenceDisState == 1 Data eg: 2#40#;3#35#;...;4#35#
                String[] tempInterferenceData = interferenceArrays[s].split("#");
                String typestr = tempInterferenceData[0];
                String powerstr = tempInterferenceData[1];
                String lonlatstr = tempInterferenceData[2];
                interferenceType[s] = Integer.parseInt(typestr);
                interferenceSourcePower[s] = Integer.parseInt(powerstr);
                if (interferenceDisState == 0) {
                    interferencePos = new double[interCount][2];
                    interferencePos[s][0] = Double.parseDouble(lonlatstr.split(",")[0]);
                    interferencePos[s][1] = Double.parseDouble(lonlatstr.split(",")[1]);
                }
            }
        }

        // 解析接收站数据
        if(!"".equals(receiveStationData) && (receiveStationData != null)){
            String receiveDataType = receiveStationData.split("#")[0];
            String receiveData = receiveStationData.split("#")[1];
            stationDistState = Integer.parseInt(receiveDataType);
            if(stationDistState == 1){
                stationInter = Double.parseDouble(receiveData);
            } else if(stationDistState == 2){
                stationNum = Integer.parseInt(receiveData);
            } else if(stationDistState == 3){
                String[] stationLocArray = receiveData.split(";");
                int stationCount = stationLocArray.length;
                stationPos = new double[stationCount][2];
                for(int i = 0; i < stationCount; i++){
                    stationPos[i][0] = Double.parseDouble(stationLocArray[i].split(",")[0]);
                    stationPos[i][1] = Double.parseDouble(stationLocArray[i].split(",")[1]);
                }
            }
        }
        log.debug("***************** 完成数据解析 *****************");
        // ********************* 调用接收站模式模型算法 *********************** //
        JSONObject jsonObject = new JSONObject();
        try {
            // ************* （1）数据仿真模块 ************* //
            engine = MatlabEngine.startMatlab();
            System.out.println("MatlabEngine ===： " + engine);
            System.out.println("jszModelPath ===： " + jszModelPath);
            engine.eval("cd " + jszModelPath);
            Object[] res = engine.feval(5, "Interference_Sim", monitor_Area, interferenceNum, interferenceSourcePower, interferenceDisState, interferencePos, interferenceType, stationDistState, stationInter, stationNum, stationPos, simTime);
//            log.debug("SimResult ===: " + res[0]); // SimResult: 仿真算法调用结果：0-失败；1-成功
//            log.debug("StationNum ===: " + res[1]); // StationNum: 监测站数量
//            log.debug("Pos ===: " + res[2]); // Pos: 监测站位置
//            log.debug("CNR ===: " + res[3]); // CNR: 监测站载噪比
//            log.debug("InterferencePos ===: " + res[4]); // InterferencePos: 干扰源位置

//            // ************ Pos Result ************ //
//            Object[] posArray = (Object[]) res[2];
//            for (int i = 0; i < posArray.length; i++) {
//                log.debug("Pos[" + i + "] === : " + posArray[i]);
//
//                double[][] PosMatrix = (double[][]) posArray[i];
//                for(int n = 0; n < PosMatrix.length; n++){
//                    log.debug("PosMatrix [" + i + "][" + n + "] X = : " + PosMatrix[n]);
//                }
//            }
//
//            // ************ CNR Result ************ //
//            Object[] CNRArray = (Object[]) res[3];
//            for (int i = 0; i < CNRArray.length; i++) {
//                // 处理每个cell内容，根据内容类型转换
//                log.debug("CNR[" + i + "] === : " + CNRArray[i]);
//
//                double[] CNRMatrix = (double[]) CNRArray[i];
//                for(int n = 0; n < CNRMatrix.length; n++){
//                    log.debug("CNRMatrix [" + i + "][" + n + "] X = : " + CNRMatrix[n]);
//                }
//            }
//
//            // ************ InterferencePos Result ************ //
//            double[][] matrixE = (double[][]) res[4];
//            for(int n = 0; n < matrixE.length; n++){
//                log.debug("InterferencePos[" + n + "] X = : " + matrixE[n][0] + "; Y = : " + matrixE[n][1]  + "; Z = : " + matrixE[n][2]);
//            }
//            log.debug("--------------------");

            // ************* （2）干扰定位模块 ************* //
            Object[] result2 =  engine.feval(2,"Interference_Location_latlon", 10, ((Object[]) res[2])[0], ((Object[]) res[3])[0]);
            log.debug("get DetectedResult ===: " + result2[0]);
            log.debug("get InterferencePos_detected ===: " + result2[1]);
            double[][] PosDetectMatrix = (double[][]) result2[1];
            for(int n = 0; n < PosDetectMatrix.length; n++){
                log.debug("InterferencePos_detected [" + n + "] X = : " + PosDetectMatrix[n][0] + "; Y = : " + PosDetectMatrix[n][1]  + "; Z = : " + PosDetectMatrix[n][2]);
            }
            log.debug("--------------------");
            // ************* （3）定位误差计算模块 ************* //

            // 构建计算后的干扰定位数据对象
            String tempCode = result2[0].toString();
            if("1.0".equals(tempCode)){
                // 创建干扰定位对象
                JSONArray locationArray = new JSONArray();
                for(int n = 0; n < PosDetectMatrix.length; n++){
                    JSONObject location = new JSONObject();
                    location.put("x", PosDetectMatrix[n][0]);
                    location.put("y", PosDetectMatrix[n][1]);
                    location.put("z", PosDetectMatrix[n][2]);
                    locationArray.add(location);
                }
                jsonObject.put("Locations", locationArray);
            }

            engine.close();
        } catch (Exception ex) {
            System.out.println(ex);
        }finally {
            if (engine == null) {
                try {
                    // 断开 Matlab 引擎连接
                    engine.disconnect();
                    log.debug("Matlab引擎已断开连接!");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        log.debug("返回的数据对象 ===： " + jsonObject.toString());
        return success(jsonObject.toString());
    }

    @GetMapping("/calcInterferenceLocation2")
    public AjaxResult calcInterferenceLocation2() {
        // 初始化模型参数对象
        double[][] Monitor_Area = {{110,25},{113,28}}; // 监测区域经纬度范围
        int InterferenceNum = 3; // 干扰源数量
        double[] InterferenceSourcePower = {40.0,40.0,40.0}; // 干扰源功率，dBw
        int InterfereneceDisState = 1; // 干扰源生成方式：0--手动输入；1--随机
        double[][] InterferencePos = null; // 干扰源位置（仅手动输入下有效）
        int[] InterferenceType = {1,1,1}; // 干扰源类型，1—单音，2—多音，3—线性扫平，4—脉冲
        int StationDistState = 1; // 监测站分布方式，1--格网部署，2--随机部署；3--位置导入
        double StationInter = 0.3; // 监测站间隔(仅限StationDistState=1格网部署下有效)
        int StationNum = 100; // 监测站数量(仅限StationDistState=2随机部署下有效)
        double[][] StationPos = null; // 监测站位置（仅限StationDistState=3位置导入下有效）
        int SimTime = 10; // 仿真时长，即输出的组数

        // ********************* 调用接收站模式模型算法 *********************** //
        JSONObject jsonObject = new JSONObject();
        MatlabEngine engine = null;
        try {
            // ************* （1）数据仿真模块 ************* //
            engine = MatlabEngine.startMatlab();
            System.out.println("MatlabEngine ===： " + engine);
            System.out.println("jszModelPath ===： " + jszModelPath);
            engine.eval("cd " + jszModelPath);
            Object[] res = engine.feval(5, "Interference_Sim", Monitor_Area, InterferenceNum, InterferenceSourcePower,InterfereneceDisState, InterferencePos, InterferenceType, StationDistState, StationInter,StationNum,StationPos,SimTime);
            System.out.println("SimResult ===: " + res[0]); // SimResult: 仿真算法调用结果：0-失败；1-成功
            System.out.println("StationNum ===: " + res[1]); // StationNum: 监测站数量
            System.out.println("Pos ===: " + res[2]); // Pos: 监测站位置
            System.out.println("CNR ===: " + res[3]); // CNR: 监测站载噪比
            System.out.println("InterferencePos ===: " + res[4]); // InterferencePos: 干扰源位置
            System.out.println("--------------------");

            // ************* （2）干扰定位模块 ************* //
            Object[] result2 =  engine.feval(2,"Interference_Location_latlon", 10, ((Object[]) res[2])[0], ((Object[]) res[3])[0]);
            System.out.println("get DetectedResult ===: " + result2[0]);
            System.out.println("get InterferencePos_detected ===: " + result2[1]);
            System.out.println("--------------------");

            // ************* （3）定位误差计算模块 ************* //
            double[][] PosDetectMatrix = (double[][]) result2[1];
            for(int n = 0; n < PosDetectMatrix.length; n++){
                System.out.println("InterferencePos_detected [" + n + "] X = : " + PosDetectMatrix[n][0] + "; Y = : " + PosDetectMatrix[n][1]  + "; Z = : " + PosDetectMatrix[n][2]);
            }

            // 构建计算后的干扰定位数据对象
            jsonObject.put("code", result2[0]);
            // 创建干扰定位对象
            JSONArray locationArray = new JSONArray();
            for(int m = 0; m < PosDetectMatrix.length; m++){
                JSONObject location = new JSONObject();
                location.put("x", PosDetectMatrix[m][0]);
                location.put("y", PosDetectMatrix[m][1]);
                location.put("z", PosDetectMatrix[m][2]);
                locationArray.add(location);
            }
            jsonObject.put("Locations", locationArray);
            System.out.println("返回的数据对象 ===： " + jsonObject.toString());
        } catch (Exception ex) {
            System.out.println(ex);
        }finally {
            try {
                engine.close();
            }catch (EngineException ex){
                System.out.println(ex);
            }
        }
        return success(jsonObject.toString());
    }

    /**
     * 获取接收站点数据列表
     */
    @PreAuthorize("@ss.hasPermi('basedata:receivestation:list')")
    @GetMapping("/list")
    public TableDataInfo list(TReceiveStation receiveStation) {
        startPage();
        List<TReceiveStation> list = receiveStationModeService.selectReceiveStationList(receiveStation);
        return getDataTable(list);
    }

    /**
     * 根据接收站主键ID获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('basedata:receivestation:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable String id) {
        TReceiveStation result = receiveStationModeService.selectReceiveStationById(id);
        return success(result);
    }

    /**
     * 新增接收站数据
     */
    @PreAuthorize("@ss.hasPermi('basedata:receivestation:add')")
    @Log(title = "接收站数据维护", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody TReceiveStation receiveStation) {
        receiveStation.setCreateTime(new Timestamp(System.currentTimeMillis()));
        return toAjax(receiveStationModeService.insertReceiveStation(receiveStation));
    }

    /**
     * 修改接收站数据
     */
    @PreAuthorize("@ss.hasPermi('basedata:receivestation:edit')")
    @Log(title = "接收站数据维护", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody TReceiveStation receiveStation) {
        return toAjax(receiveStationModeService.updateReceiveStation(receiveStation));
    }

    /**
     * 删除接收站数据
     */
    @PreAuthorize("@ss.hasPermi('basedata:receivestation:remove')")
    @Log(title = "接收站数据维护", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(receiveStationModeService.deleteReceiveStationByIds(ids));
    }

    //************************** V2 模型算法接口 **************************//
    /**
     * V2-1：获取监测站和卫星位置接口
     * @param monitroArea 监测区域经纬度范围
     * @param stationDistState 监测站分布方式，1-格网部署，2-随机部署；3-位置导入
     * @param stationInterStr 监测站间隔(1-格网部署时有效)
     * @param monitorStationData 监测站数据
     * @return
     */
    @GetMapping("/receiverSim")
    public AjaxResult receiverSim(String monitroArea, String stationDistState, String stationInterStr, String stationNumStr, String monitorStationData) {
        log.debug("*****V2-1开始执行*****");
        double stationInter = 0.3;
        int stationNum = 10;
        double[][] monitor_Area = null; // 监测区域经纬度范围
        double[][] stationPos = null; // 监测站位置（stationDistState=3位置导入时有效）
        int stationDisStateInt = -1;
        stationDisStateInt = Integer.parseInt(stationDistState);
        if (stationDisStateInt == 1) {
            stationInter = Double.parseDouble(stationInterStr);
        }
        if (stationDisStateInt == 2) {
            stationNum = Integer.parseInt(stationNumStr);
        }
        if (stationDisStateInt == 3) {
            log.debug("monitorStationData ===: " + monitorStationData);
            String[] stationLocArray = monitorStationData.split(";");
            int stationCount = stationLocArray.length;
            stationPos = new double[stationCount][2];
            for (int i = 0; i < stationCount; i++) {
                stationPos[i][0] = Double.parseDouble(stationLocArray[i].split(",")[0]);
                stationPos[i][1] = Double.parseDouble(stationLocArray[i].split(",")[1]);
            }
            stationNum = stationCount;
        }

        // 解析监测区域经纬度范围
        if (!"".equals(monitroArea) && monitroArea != null) {
            String[] pointArray = monitroArea.split(";");
            double point1lon = Double.parseDouble(pointArray[0].split(",")[0]);
            double point1lat = Double.parseDouble(pointArray[0].split(",")[1]);
            double point2lon = Double.parseDouble(pointArray[1].split(",")[0]);
            double point2lat = Double.parseDouble(pointArray[1].split(",")[1]);
            monitor_Area = new double[][]{{point1lon, point1lat}, {point2lon, point2lat}};
        }

        JSONObject jsonObject = new JSONObject();
        try {
            // ************* （1）监测站和卫星 ************* //
            // engine = MatlabEngine.startMatlab();
            engine = this.getInstance();
            log.debug("MatlabEngine ===： " + engine);
            engine.eval("cd " + jszModelPath);
            for(int n=0; n< monitor_Area.length; n++){
                log.debug("monitor_Area [" + n + "] ===: " + monitor_Area[n][0]);
                log.debug("monitor_Area [" + n + "] ===: " + monitor_Area[n][1]);
            }
            log.debug("stationDisStateInt ===: " + stationDisStateInt);
            log.debug("stationInter ===: " + stationInter);
            log.debug("stationNum ===: " + stationNum);

            Object[] res = engine.feval(2, "Receiver_Sim", monitor_Area, stationDisStateInt, stationInter, stationNum, stationPos);
            log.debug("receiver_pos ===: " + res[0]); // receiver_pos: 监测站的位置
            log.debug("satellite_pos ===: " + res[1]); // satellite_pos: 卫星的位置

            // ************ 结果解析 ************ //
            // 解析接收站位置信息
            double[][] receiverPosArray = (double[][]) res[0];
            JSONArray receiverPosJsonArray = new JSONArray();
            for (int i = 0; i < receiverPosArray.length; i++) {
                // log.debug("receiver pos [" + i + "] X =: " + receiverPosArray[i][0] + "; Y =: " + receiverPosArray[i][1] + "; Z =: " + receiverPosArray[i][2]);
                log.debug("receiver pos [" + i + "] X =: " + receiverPosArray[i][0] + "; Y =: " + receiverPosArray[i][1]);
                JSONObject location = new JSONObject();
                location.put("rpx", receiverPosArray[i][0]);
                location.put("rpy", receiverPosArray[i][1]);
                // location.put("rpz", receiverPosArray[i][2]);
                receiverPosJsonArray.add(location);
            }
            // 解析卫星位置信息
            double[][] satellitePosArray = (double[][]) res[1];
            JSONArray satellitePosJsonArray = new JSONArray();
            for (int i = 0; i < satellitePosArray.length; i++) {
                log.debug("satellite pos [" + i + "] X =: " + satellitePosArray[i][0] + "; Y =: " + satellitePosArray[i][1] + "; Z =: " + satellitePosArray[i][2]);
                JSONObject location = new JSONObject();
                location.put("spx", satellitePosArray[i][0]);
                location.put("spy", satellitePosArray[i][1]);
                location.put("spz", satellitePosArray[i][2]);
                satellitePosJsonArray.add(location);
            }
            jsonObject.put("ReceiverPos", receiverPosJsonArray);
            jsonObject.put("SatellitePos", satellitePosJsonArray);
            log.debug("返回的数据对象 ===： " + jsonObject.toString());
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
//        finally {
//            try {
//                engine.close();
//            } catch (EngineException ex) {
//                log.error(ex.getMessage());
//            }
//        }
        return AjaxResult.success(jsonObject.toString());
    }

    /**
     * V2-2：获取干扰源位置接口
     * @param monitorArea 监测区域经纬度范围
     * @param interferenceDistState 干扰源分布方式，0-位置导入，1-随机部署
     * @param interferencePos 干扰源经纬度坐标(0-位置导入时有效)
     * @param interferenceNum 干扰源数量(1-随机部署时有效)
     * @param interferenceSourcePower 各干扰源发射功率
     * @param interferenceType 各干扰源类型（1-单音，2-多音，3-线性扫频，4-脉冲）
     * @return
     */
    @GetMapping("/interferenceSim")
    public AjaxResult interferenceSim(String monitorArea, String interferenceDistState, String interferencePos, String interferenceNum,
                                   String interferenceSourcePower, String interferenceType){
        log.debug("*****V2-2开始执行*****");
        int interferenceNumInt = -1;
        double[][] monitor_Area = null; // 监测区域经纬度范围
        double[][] interferencePosArray = null; // 干扰源位置
        double[] InterferenceSourcePower = null; // 干扰源功率，dBw
        int[] InterferenceType = null; // 干扰源类型
        int interferenceDistStateInt = Integer.parseInt(interferenceDistState);

        // 解析干扰源经纬度坐标
        if ("0".equals(interferenceDistState)) {
            String[] interferencePoss = interferencePos.split(";");
            int interferenceCount = interferencePoss.length;
            interferencePosArray = new double[interferenceCount][2];
            for (int i = 0; i < interferenceCount; i++) {
                interferencePosArray[i][0] = Double.parseDouble(interferencePoss[i].split(",")[0]);
                interferencePosArray[i][1] = Double.parseDouble(interferencePoss[i].split(",")[1]);
            }
        }

        if ("1".equals(interferenceDistState)) {
            interferenceNumInt = Integer.parseInt(interferenceNum);
        }

        // 解析监测区域经纬度范围
        if (!"".equals(monitorArea) && monitorArea != null) {
            String[] pointArray = monitorArea.split(";");
            double point1lon = Double.parseDouble(pointArray[0].split(",")[0]);
            double point1lat = Double.parseDouble(pointArray[0].split(",")[1]);
            double point2lon = Double.parseDouble(pointArray[1].split(",")[0]);
            double point2lat = Double.parseDouble(pointArray[1].split(",")[1]);
            monitor_Area = new double[][]{{point1lon, point1lat}, {point2lon, point2lat}};
        }

        // 解析干扰源发射功率
        if (!"".equals(interferenceSourcePower) && interferenceSourcePower != null) {
            String[] powerArray = interferenceSourcePower.split(",");
            InterferenceSourcePower = new double[powerArray.length];
            for (int i = 0; i < powerArray.length; i++) {
                InterferenceSourcePower[i] = Double.parseDouble(powerArray[i]);
            }
        }

        if(!"".equals(interferenceType) && interferenceType != null){
            String[] interferenceTypeArray = interferenceType.split(",");
            InterferenceType = new int[interferenceTypeArray.length];
            for (int i = 0; i < interferenceTypeArray.length; i++) {
                InterferenceType[i] = Integer.parseInt(interferenceTypeArray[i]);
            }
        }

        JSONObject jsonObject = new JSONObject();
        try {
            // engine = MatlabEngine.startMatlab();
            engine = this.getInstance();
            engine.eval("cd " + jszModelPath);
            Object[] res = engine.feval(4, "Interference_Sim", monitor_Area, interferenceDistStateInt, interferencePosArray,
                    interferenceNumInt, InterferenceSourcePower, InterferenceType);
            log.debug("InterferencePos ===: " + res[0]); // InterferencePos: 干扰源的位置
            log.debug("InterferenceNum ===: " + res[1]); // InterferenceNum: 干扰源数量
            log.debug("InterferenceSourcePower ===: " + res[2]); // InterferenceSourcePower: 干扰源发射功率
            log.debug("InterferenceType ===: " + res[3]); // InterferenceType：干扰源类型

            // ************ 结果解析 ************ //
            // 解析干扰源位置信息
            double[][] tempInterferencePos = (double[][]) res[0];
            JSONArray interferencePosJsonArray = new JSONArray();
            for (int i = 0; i < tempInterferencePos.length; i++) {
                log.debug("Interference Pos [" + i + "] X =: " + tempInterferencePos[i][0] + "; Y =: " + tempInterferencePos[i][1]);
                JSONObject location = new JSONObject();
                location.put("ipx", tempInterferencePos[i][0]);
                location.put("ipy", tempInterferencePos[i][1]);
                interferencePosJsonArray.add(location);
            }

            // 解析干扰源发射功率
            double[] tempInterferenceSourcePower = (double[]) res[2];
            JSONArray interferenceSourcePowerJsonArray = new JSONArray();
            for (int i = 0; i < tempInterferenceSourcePower.length; i++) {
                log.debug("Interference Source Power [" + i + "] =: " + tempInterferenceSourcePower[i]);
                JSONObject location = new JSONObject();
                location.put("power", tempInterferenceSourcePower[i]);
                interferenceSourcePowerJsonArray.add(location);
            }

            // 解析干扰源类型
            int[] tempInterferenceType = (int[]) res[3];
            JSONArray interferenceTypeJsonArray = new JSONArray();
            for (int i = 0; i < tempInterferenceType.length; i++) {
                log.debug("Interference Type [" + i + "] =: " + tempInterferenceType[i]);
                JSONObject location = new JSONObject();
                location.put("type", tempInterferenceType[i]);
                interferenceTypeJsonArray.add(location);
            }
            jsonObject.put("InterferencePos", interferencePosJsonArray);
            jsonObject.put("InterferenceSourcePower", interferenceSourcePowerJsonArray);
            jsonObject.put("InterferenceType", interferenceTypeJsonArray);
            log.debug("返回的数据对象 ===： " + jsonObject.toString());
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
//        finally {
//            try {
//                engine.close();
//            } catch (EngineException ex) {
//                log.error(ex.getMessage());
//            }
//        }
        return AjaxResult.success(jsonObject.toString());
    }

    /**
     * V2-3: 载噪比仿真
     * @param receiverPos 监测站的位置（第1步的输出）
     * @param satellitePos 卫星的位置（第1步的输出）
     * @param interferencePos 干扰源的位置（第2步的输出）
     * @param interferenceNum 干扰源的数量（第2步的输出）
     * @param interferenceSourcePower 各干扰源的发射功率（第2步的输出）
     * @param interferenceType 各干扰源的类型（第2步的输出）
     * @param simTime 仿真次数（生成多少组载噪比）
     * @return StationPos(监测站位置坐标) 和 StationCNR_t(载噪比数据) 和 InterferencePos(真实干扰源位置坐标)
     */
    @GetMapping("/signalSim")
    public AjaxResult signalSim(String receiverPos, String satellitePos, String interferencePos, int interferenceNum,
                                 String interferenceSourcePower, String interferenceType, int simTime){
        log.debug("*****V2-3开始执行*****");
        if ("".equals(receiverPos) || receiverPos == null) {
            return error("接收站位置数据为空");
        }
        if ("".equals(satellitePos) || satellitePos == null) {
            return error("卫星位置数据为空");
        }
        if ("".equals(interferencePos) || interferencePos == null) {
            return error("干扰源位置数据为空");
        }

        String[] receiverPoss = receiverPos.split(";");
        int receiverCount = receiverPoss.length;
        double[][] receiverPosArray = new double[receiverCount][2];
        for (int i = 0; i < receiverCount; i++) {
            receiverPosArray[i][0] = Double.parseDouble(receiverPoss[i].split(",")[0]);
            receiverPosArray[i][1] = Double.parseDouble(receiverPoss[i].split(",")[1]);
        }

        String[] satellitePoss = satellitePos.split(";");
        int satelliteCount = satellitePoss.length;
        double[][] satellitePosArray = new double[satelliteCount][2];
        for (int i = 0; i < satelliteCount; i++) {
            satellitePosArray[i][0] = Double.parseDouble(satellitePoss[i].split(",")[0]);
            satellitePosArray[i][1] = Double.parseDouble(satellitePoss[i].split(",")[1]);
        }

        String[] interferencePoss = interferencePos.split(";");
        int interferenceCount = interferencePoss.length;
        double[][] interferencePosArray = new double[interferenceCount][2];
        for (int i = 0; i < interferenceCount; i++) {
            interferencePosArray[i][0] = Double.parseDouble(interferencePoss[i].split(",")[0]);
            interferencePosArray[i][1] = Double.parseDouble(interferencePoss[i].split(",")[1]);
        }

        // 解析干扰源发射功率
        double[] interferenceSourcePowerArray = null; // 干扰源功率，dBw
        if (!"".equals(interferenceSourcePower) && interferenceSourcePower != null) {
            String[] powerArray = interferenceSourcePower.split(",");
            interferenceSourcePowerArray = new double[powerArray.length];
            for (int i = 0; i < powerArray.length; i++) {
                interferenceSourcePowerArray[i] = Double.parseDouble(powerArray[i]);
            }
        }

        double[] interferenceTypeArray = null; // 干扰源类型
        if (!"".equals(interferenceType) && interferenceType != null) {
            String[] typeArray = interferenceType.split(",");
            interferenceTypeArray = new double[typeArray.length];
            for (int i = 0; i < typeArray.length; i++) {
                interferenceTypeArray[i] = Integer.parseInt(typeArray[i]);
            }
        }

        JSONObject jsonObject = new JSONObject();
        try {
            // engine = MatlabEngine.startMatlab();
            engine = this.getInstance();
            engine.eval("cd " + jszModelPath);
            Object[] res = engine.feval(3, "Signal_Sim", receiverPosArray, satellitePosArray, interferencePosArray,
                    interferenceNum, interferenceSourcePowerArray, interferenceTypeArray, simTime);
            log.debug("StationPos ===: " + res[0]); // StationPos: 监测站位置坐标（现在只有一组位置了）
            log.debug("StationCNR_t ===: " + res[1]); // StationCNR_t: 载噪比数据（多少组/行取决于仿真次数）
            log.debug("InterferencePos ===: " + res[2]); // InterferencePos: 真实干扰源位置坐标

            // ************ 结果解析 ************ //
            // 解析监测站位置坐标
            double[][] tempStationPos = (double[][]) res[0];
            JSONArray stationPosJsonArray = new JSONArray();
            for (int i = 0; i < tempStationPos.length; i++) {
                log.debug("StationPos [" + i + "] X =: " + tempStationPos[i][0] + "; Y =: " + tempStationPos[i][1]);
                JSONObject location = new JSONObject();
                location.put("spx", tempStationPos[i][0]);
                location.put("spy", tempStationPos[i][1]);
                // location.put("spz", tempStationPos[i][2]);
                stationPosJsonArray.add(location);
            }

            // 解析载噪比数据
            JSONArray stationCNRJsonArray = new JSONArray();
            if (simTime == 1) {
                double[] stationCNRArray = (double[]) res[1];
                JSONObject location = new JSONObject();
                String tempStationCNRStr = new String();
                for (int i = 0; i < stationCNRArray.length; i++) {
                    tempStationCNRStr += stationCNRArray[i] + ",";
                }
                location.put("CNR", tempStationCNRStr.substring(0, tempStationCNRStr.length() - 1));
                stationCNRJsonArray.add(location);
            } else {
                double[][] stationCNRArray = (double[][]) res[1];
                JSONObject location = null;
                for (int i = 0; i < stationCNRArray.length; i++) {
                    location = new JSONObject();
                    String tempStationCNRStr = new String();
                    for (int s = 0; s < receiverCount; s++) {
                        tempStationCNRStr += stationCNRArray[i][s] + ",";
                    }
                    location.put("CNR", tempStationCNRStr.substring(0, tempStationCNRStr.length() - 1));
                    stationCNRJsonArray.add(location);
                }
            }

            // 解析真实干扰源位置坐标
            double[][] InterferencePos = (double[][]) res[2];
            JSONArray interferencePosJsonArray = new JSONArray();
            for (int i = 0; i < InterferencePos.length; i++) {
                // log.debug("Interference [" + i + "] X =: " + Interference[i][0] + "; Y =: " + Interference[i][1] + "; Z =: " + Interference[i][2]);
                JSONObject location = new JSONObject();
                location.put("ifx", InterferencePos[i][0]);
                location.put("ify", InterferencePos[i][1]);
                // location.put("ifz", Interference[i][2]);
                interferencePosJsonArray.add(location);
            }

            jsonObject.put("StationPos", stationPosJsonArray);
            jsonObject.put("StationCNR_t", stationCNRJsonArray);
            jsonObject.put("Interference", interferencePosJsonArray);
            log.debug("返回的数据对象 ===： " + jsonObject.toString());
        } catch (Exception ex) {
            log.error(ex.getMessage());
            return error("载噪比仿真接口处理异常");
        }
        return success(jsonObject.toString());
    }

    /**
     * V2-4: 干扰定位
     * @param stationPos 监测站位置（第3步的输出）
     * @param stationCNRT 监测站载噪比(取第3步输出的某一行作为输入)
     * @return DetectedResult(算法调用结果：0-失败；1-成功) 和 InterferencePos_detected（定位到的干扰源位置）
     */
    @GetMapping("/interferenceLocationLatlon")
    public AjaxResult interferenceLocationLatlon(String stationPos, String stationCNRT){
        log.debug("*****V2-4开始执行*****");
        log.debug("stationPos parameter ===: " + stationPos);
        log.debug("stationCNRT parameter ===: " + stationCNRT);

        if ("".equals(stationPos) || stationPos == null) {
            return error("接收站位置数据为空");
        }
        if ("".equals(stationCNRT) || stationCNRT == null) {
            return error("卫星位置数据为空");
        }

        String[] receiverPoss = stationPos.split(";");
        int receiverCount = receiverPoss.length;
        double[][] receiverPosArray = new double[receiverCount][3];
        for (int i = 0; i < receiverCount; i++) {
            receiverPosArray[i][0] = Double.parseDouble(receiverPoss[i].split(",")[0]);
            receiverPosArray[i][1] = Double.parseDouble(receiverPoss[i].split(",")[1]);
            // receiverPosArray[i][2] = Double.parseDouble(receiverPoss[i].split(",")[2]);
        }

        String[] tempStationCNRT = stationCNRT.split(",");
        int stationCNRTCount = tempStationCNRT.length;
        double[] stationCNRTArray = new double[stationCNRTCount];
        for (int i = 0; i < stationCNRTCount; i++) {
            stationCNRTArray[i] = Double.parseDouble(tempStationCNRT[i]);
        }

        JSONObject jsonObject = new JSONObject();
        try {
            engine = this.getInstance();
            // engine = MatlabEngine.startMatlab();
            engine.eval("cd " + jszModelPath);
            Object[] res = engine.feval(2, "Interference_Location_latlon", receiverPosArray, stationCNRTArray);
            log.debug("DetectedResult ===: " + res[0]); // DetectedResult: 算法调用结果：0-失败；1-成功
            log.debug("InterferencePos_detected ===: " + res[1]); // InterferencePos_detected: 定位到的干扰源位置

            // ************ 结果解析 ************ //
            // 解析算法调用结果
            double detectedResult = (double) res[0];
            if(detectedResult == 0){
                return error("干扰定位算法调用无结果。");
            }

            // 解析定位到的干扰源位置
            double[][] tempInterferencePosDetected = (double[][]) res[1];
            JSONArray interferencePosDetectedJsonArray = new JSONArray();
            for (int i = 0; i < tempInterferencePosDetected.length; i++) {
                log.debug("StationPos [" + i + "] X =: " + tempInterferencePosDetected[i][0] + "; Y =: " + tempInterferencePosDetected[i][1]);
                JSONObject location = new JSONObject();
                location.put("ifpdx", tempInterferencePosDetected[i][0]);
                location.put("ifpdy", tempInterferencePosDetected[i][1]);
                location.put("ifpdz", tempInterferencePosDetected[i][2]);
                interferencePosDetectedJsonArray.add(location);
            }
            jsonObject.put("detectedInterferencePos", interferencePosDetectedJsonArray);
            log.debug("返回的数据对象 ===： " + jsonObject.toString());
        } catch (Exception ex) {
            log.error(ex.getMessage());
            return error("干扰定位接口处理异常");
        }
        return success(jsonObject.toString());
    }

    /**
     * V2-5: 定位误差计算
     * @param interferencePostion 真实干扰源位置
     * @param interferencePostionDetected 定位到的干扰源位置
     * @return LocationError(每个干扰源的定位误差) 和 LocationError_avg(总平均定位误差)
     */
    @GetMapping("/calculateLocationError")
    public AjaxResult calculateLocationError(String interferencePostion, String interferencePostionDetected){
        log.debug("*****V2-5开始执行*****");
        log.debug("interferencePostion parameter ===：" + interferencePostion);
        log.debug("interferencePostionDetected parameter ===：" + interferencePostionDetected);
        String[] interferencePostions = interferencePostion.split(";");
        int interferencePostionsCount = interferencePostions.length;
        double[][] interferencePostionArray = new double[interferencePostionsCount][3];
        for (int i = 0; i < interferencePostionsCount; i++) {
            interferencePostionArray[i][0] = Double.parseDouble(interferencePostions[i].split(",")[0]);
            interferencePostionArray[i][1] = Double.parseDouble(interferencePostions[i].split(",")[1]);
            interferencePostionArray[i][2] = Double.parseDouble(interferencePostions[i].split(",")[2]);
        }

        String[] interferencePostionDetecteds = interferencePostionDetected.split(";");
        int interferencePostionDetectedCount = interferencePostionDetecteds.length;
        double[][] interferencePostionDetectedArray = new double[interferencePostionDetectedCount][3];
        for (int i = 0; i < interferencePostionDetectedCount; i++) {
            interferencePostionDetectedArray[i][0] = Double.parseDouble(interferencePostionDetecteds[i].split(",")[0]);
            interferencePostionDetectedArray[i][1] = Double.parseDouble(interferencePostionDetecteds[i].split(",")[1]);
            interferencePostionDetectedArray[i][2] = Double.parseDouble(interferencePostionDetecteds[i].split(",")[2]);
        }

        JSONObject jsonObject = new JSONObject();
        try {
            engine = this.getInstance();
            // engine = MatlabEngine.startMatlab();
            engine.eval("cd " + jszModelPath);
            Object[] res = engine.feval(2, "calculateLocationError", interferencePostionArray, interferencePostionDetectedArray);
            log.debug("LocationError ===: " + res[0]); // 每个干扰源的定位误差
            log.debug("LocationError_avg ===: " + res[1]); // 总平均定位误差

            // ************ 结果解析 ************ //
            // 解析每个干扰源的定位误差
            double[] locationErrorResult = (double[]) res[0];
            JSONArray locationErrorJsonArray = new JSONArray();
            for (int i = 0; i < locationErrorResult.length; i++) {
                log.debug("LocationError [" + i + "] =: " + locationErrorResult[i]);
                locationErrorJsonArray.add(locationErrorResult[i]);
            }

            // 解析总平均定位误差
            double LocationErrorAvgResult = (double) res[1];

            jsonObject.put("LocationError", locationErrorJsonArray);
            jsonObject.put("LocationErrorAvg", LocationErrorAvgResult);
            log.debug("返回的数据对象 ===： " + jsonObject.toString());
        } catch (Exception ex) {
            log.error(ex.getMessage());
            return error("定位误差计算接口处理异常");
        }
        return success(jsonObject.toString());
    }

    /**
     * V2-6: 集成载噪比仿真、干扰定位和定位误差计算接口
     * @param receiverPos 监测站的位置
     * @param satellitePos 卫星的位置
     * @param interferencePos 干扰源的位置
     * @param interferenceNum 干扰源的数量
     * @param interferenceSourcePower 各干扰源的发射功率
     * @param interferenceType 各干扰源的类型
     * @param simTime 仿真次数
     * @return InterferencePos_detected（定位到的干扰源位置） 和 统计结果
     */
    @GetMapping("/interferenceAnalyzeStatic")
    public AjaxResult interferenceAnalyzeStatic(String receiverPos, String satellitePos, String interferencePos, int interferenceNum,
                                                String interferenceSourcePower, String interferenceType, int simTime){
        log.debug("*****V2-6开始执行*****");
        log.debug("receiverPos parameter ===: " + receiverPos);
        log.debug("satellitePos parameter ===: " + satellitePos);
        log.debug("interferencePos parameter ===: " + interferencePos);
        log.debug("interferenceNum parameter ===: " + interferenceNum);
        log.debug("interferenceSourcePower parameter ===: " + interferenceSourcePower);
        log.debug("interferenceType parameter ===: " + interferenceType);
        log.debug("simTime parameter ===: " + simTime);

        String[] receiverPoss = receiverPos.split(";");
        int receiverCount = receiverPoss.length;
        double[][] receiverPosArray = new double[receiverCount][3];
        for (int i = 0; i < receiverCount; i++) {
            receiverPosArray[i][0] = Double.parseDouble(receiverPoss[i].split(",")[0]);
            receiverPosArray[i][1] = Double.parseDouble(receiverPoss[i].split(",")[1]);
            receiverPosArray[i][2] = Double.parseDouble(receiverPoss[i].split(",")[2]);
        }

        String[] satellitePoss = satellitePos.split(";");
        int satelliteCount = satellitePoss.length;
        double[][] satellitePosArray = new double[satelliteCount][3];
        for (int i = 0; i < satelliteCount; i++) {
            satellitePosArray[i][0] = Double.parseDouble(satellitePoss[i].split(",")[0]);
            satellitePosArray[i][1] = Double.parseDouble(satellitePoss[i].split(",")[1]);
            satellitePosArray[i][2] = Double.parseDouble(satellitePoss[i].split(",")[2]);
        }

        String[] interferencePoss = interferencePos.split(";");
        int interferenceCount = interferencePoss.length;
        double[][] interferencePosArray = new double[interferenceCount][3];
        for (int i = 0; i < interferenceCount; i++) {
            interferencePosArray[i][0] = Double.parseDouble(interferencePoss[i].split(",")[0]);
            interferencePosArray[i][1] = Double.parseDouble(interferencePoss[i].split(",")[1]);
            interferencePosArray[i][2] = Double.parseDouble(interferencePoss[i].split(",")[2]);
        }

        // 解析干扰源发射功率
        double[] interferenceSourcePowerArray = null; // 干扰源功率，dBw
        if (!"".equals(interferenceSourcePower) && interferenceSourcePower != null) {
            String[] powerArray = interferenceSourcePower.split(",");
            interferenceSourcePowerArray = new double[powerArray.length];
            for (int i = 0; i < powerArray.length; i++) {
                interferenceSourcePowerArray[i] = Double.parseDouble(powerArray[i]);
            }
        }

        double[] interferenceTypeArray = null; // 干扰源类型
        if (!"".equals(interferenceType) && interferenceType != null) {
            String[] typeArray = interferenceType.split(",");
            interferenceTypeArray = new double[typeArray.length];
            for (int i = 0; i < typeArray.length; i++) {
                interferenceTypeArray[i] = Integer.parseInt(typeArray[i]);
            }
        }

        JSONObject jsonObject = new JSONObject();
        try {
            engine = this.getInstance();
            engine.eval("cd " + jszModelPath);
            //****************************** Step 1 **********************************//
            log.debug("***** V2-6 Step 1 begin *****");
            Object[] res1 = engine.feval(3, "Signal_Sim", receiverPosArray, satellitePosArray, interferencePosArray,
                    interferenceNum, interferenceSourcePowerArray, interferenceTypeArray, simTime);
            log.debug("StationPos ===: " + res1[0]); // StationPos: 监测站位置坐标（现在只有一组位置了）
            log.debug("StationCNR_t ===: " + res1[1]); // StationCNR_t: 载噪比数据（多少组/行取决于仿真次数）
            log.debug("InterferencePos ===: " + res1[2]); // InterferencePos: 真实干扰源位置坐标

            // ************ 解析载噪比分析结果 ************ //
            // 解析监测站位置坐标
            double[][] tempStationPos = (double[][]) res1[0];

            // 解析载噪比数据
            double[][] stationCNR2Array = null;
            if (simTime == 1) {
                double[] stationCNRArray = (double[]) res1[1];
                stationCNR2Array = new double[1][stationCNRArray.length];
                for (int i = 0; i < stationCNRArray.length; i++) {
                    stationCNR2Array[1][i] = stationCNRArray[i];
                }
            } else {
                stationCNR2Array = (double[][]) res1[1];
            }
            log.debug("stationCNR2Array ===: " + stationCNR2Array);

            // 解析真实干扰源位置坐标
            double[][] tempInterferencePos = (double[][]) res1[2];

            //****************************** Step 2 **********************************//
            log.debug("***** V2-6 Step 2 begin *****");
            JSONArray simTimeInterferencePosDetectedJsonArray = new JSONArray();
            JSONArray simTimeLocationErrorJsonArray = new JSONArray();
            JSONArray simTimeLocationErrorAvgJsonArray = new JSONArray();

            for(int i = 0; i < stationCNR2Array.length; i++){
                Object[] res2 = engine.feval(2, "Interference_Location_latlon", tempStationPos, stationCNR2Array[i]);
                log.debug("DetectedResult ===: " + res2[0]); // 算法调用结果：0-失败；1-成功
                log.debug("InterferencePos_detected ===: " + res2[1]); // 定位到的干扰源位置
                double[][] tempInterferencePosDetected = (double[][]) res2[1];
                JSONArray oneIFPosDetectedJsonArray = new JSONArray();
                for (int s = 0; s < tempInterferencePosDetected.length; s++) {
                    log.debug("StationPos [" + s + "] X =: " + tempInterferencePosDetected[s][0] + "; Y =: " + tempInterferencePosDetected[s][1]);
                    JSONObject location = new JSONObject();
                    location.put("ifpdx", tempInterferencePosDetected[s][0]);
                    location.put("ifpdy", tempInterferencePosDetected[s][1]);
                    location.put("ifpdz", tempInterferencePosDetected[s][2]);
                    oneIFPosDetectedJsonArray.add(location);
                }
                simTimeInterferencePosDetectedJsonArray.add(oneIFPosDetectedJsonArray);

                //****************************** Step 3 **********************************//
                log.debug("***** V2-6 Step 3 [" + i + "] begin *****");
                double[][] zzz = new double[3][3];
                zzz[0][0] = 110.02162448286161;
                zzz[0][1] = 24.970755200346044;
                zzz[0][2] = 0.0;
                zzz[1][0] = 112.65747916918892;
                zzz[1][1] = 26.59007657281241;
                zzz[1][2] = 0.0;
                zzz[2][0] = 111.25747916918892;
                zzz[2][1] = 25.19007657281241;
                zzz[2][2] = 0.0;
                /**
                 * @TODO 恢复下面一行代码，和小程构成当计算的干扰源数量小于真实的干扰源数量时报错的问题
                 */
                // Object[] res3 = engine.feval(2, "calculateLocationError", interferencePosArray, tempInterferencePosDetected);
                Object[] res3 = engine.feval(2, "calculateLocationError", interferencePosArray, zzz);
                log.debug("LocationError ===: " + res3[0]); // 每个干扰源的定位误差
                log.debug("LocationError_avg ===: " + res3[1]); // 总平均定位误差

                // ************ 结果解析 ************ //
                // 解析每个干扰源的定位误差
                double[] locationErrorResult = (double[]) res3[0];
                JSONArray locationErrorJsonArray = new JSONArray();
                for (int n = 0; n < locationErrorResult.length; n++) {
                    log.debug("LocationError [" + n + "] =: " + locationErrorResult[n]);
                    locationErrorJsonArray.add(locationErrorResult[n]);
                }
                simTimeLocationErrorJsonArray.add(locationErrorJsonArray);

                // 解析总平均定位误差
                double LocationErrorAvgResult = (double) res3[1];
                simTimeLocationErrorAvgJsonArray.add(LocationErrorAvgResult);
            }

            // ************ 返回结果 ************ //
            jsonObject.put("NTimeInterferencePosDetected", simTimeInterferencePosDetectedJsonArray);
            jsonObject.put("NTimeLocationError", simTimeLocationErrorJsonArray);
            jsonObject.put("NTimeLocationErrorAvg", simTimeLocationErrorAvgJsonArray);
            log.debug("返回的数据对象 ===： " + jsonObject.toString());
        } catch (Exception ex) {
            log.error(ex.getMessage());
            return error("载噪比仿真接口处理异常");
        }
        return success(jsonObject.toString());
    }

    /**
     * 保存接收站分析过程及成果数据。
     * @param name 监测区域经纬度范围，eg：x1,y1;x2,y2
     * @param result 监测站分布方式，1-格网部署，2-随机部署；3-位置导入, eg: 1/2/3
     * @return
     */
    @PostMapping("/saveJszAnalyseData")
    public AjaxResult saveJszAnalyseData(@RequestBody TJszHistoryData jszHistoryData) {
        int flag = receiveStationModeService.saveJszAnalyseData(jszHistoryData);
        if(flag == 1){
            return AjaxResult.success("接收站模式分析过程数据保存成功");
        }
        return AjaxResult.error("接收站模式分析过程数据保存失败。");
    }

    /**
     * 查询接收站模式数据
     * @param lastCount
     * @param lastCount
     * @return
     */
    @GetMapping("/queryJszLastRecord")
    public AjaxResult queryJszLastRecord(int lastCount){
        List<TJszHistoryData> jszHistoryDataList = receiveStationModeService.queryJszLastRecordList(lastCount);
        return AjaxResult.success(jszHistoryDataList);
    }

    /**
     * 根据ID查询接收站模式下的历史分析过程数据
     * @param id
     * @return
     */
    @GetMapping("/getJszRecordById")
    public AjaxResult getJszRecordById(int id){
        TJszHistoryData jszHistoryData = receiveStationModeService.getJszRecordById(id);
        return AjaxResult.success(jszHistoryData);
    }

}
